package com.xiaouyudeguang.common.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

@Component
public class OSSConfig {

    @Value("${aliyun.oss.endpoint:}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId:}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret:}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName:}")
    private String bucketName;
    @Value("${aliyun.oss.urlPrefix:}")
    private String urlPrefix;

    /**
     * 上传文件，以IO流方式
     *
     * @param inputStream 输入流
     * @param objectName  唯一objectName（在oss中的文件名字）
     */
    public String upload(InputStream inputStream, String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(parseType(objectName));
        ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
        ossClient.shutdown();
        return objectName;
    }

    /**
     * 上传单个文件到OSS
     *
     * @param file       要上传的文件File对象
     * @param objectName 上传后的文件名，包含文件夹，比如 game/game/test.txt
     * @return
     */
    public String upload(File file, String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(parseType(objectName));
        ossClient.putObject(bucketName, objectName, file, objectMetadata);
        ossClient.shutdown();
        return urlPrefix + objectName;
    }


    /**
     * 删除OSS中的单个文件
     *
     * @param objectName 唯一objectName（在oss中的文件名字）
     */
    public void delete(String objectName) {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除OSS中的文件
     *
     * @param objectNames oss中文件名list
     */
    public void delete(List<String> objectNames) {
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 批量删除文件。
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNames));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件临时url
     *
     * @param objectName    oss中的文件名
     * @param effectiveTime 有效时间(ms)
     */
    public String getUrl(String objectName, long effectiveTime) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间
        Date expiration = new Date(new Date().getTime() + effectiveTime);
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

    public static String parseType(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (suffix.equalsIgnoreCase("BMP") || suffix.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (suffix.equalsIgnoreCase("GIF") || suffix.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (suffix.equalsIgnoreCase("MP4") || suffix.equalsIgnoreCase("mp4")) {
            return "video/mp4";
        }
        if (suffix.equalsIgnoreCase("JPEG")
                || suffix.equalsIgnoreCase("jpeg")
                || suffix.equalsIgnoreCase("JPG")
                || suffix.equalsIgnoreCase("jpg")
                || suffix.equalsIgnoreCase("PNG")
                || suffix.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (suffix.equalsIgnoreCase("HTML") || suffix.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (suffix.equalsIgnoreCase("TXT") || suffix.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (suffix.equalsIgnoreCase("VSD") || suffix.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (suffix.equalsIgnoreCase("PPTX")
                || suffix.equalsIgnoreCase("pptx")
                || suffix.equalsIgnoreCase("PPT")
                || suffix.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (suffix.equalsIgnoreCase("DOCX")
                || suffix.equalsIgnoreCase("docx")
                || suffix.equals("DOC")
                || suffix.equals("doc")) {
            return "application/msword";
        }
        if (suffix.equalsIgnoreCase("XML") || suffix.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

}

